<!--
 * @Author: Nico
-->
<template>
  <div v-if="info.list.length != 0" class="batchHeader flex mt-2" :class="{ hidden: conditionProperty.hidden }">
    <p>{{ translateTitle('Ve.elements.批次属性') }}</p>
    <van-icon class="ml-1" :name="isShowBatch ? 'eye-o' : 'closed-eye'" @click="isShowBatch = !isShowBatch" />
  </div>
  <template v-if="!hasPreview">
    <div class="ui-dynamic-form" style="overflow: hidden">
      <van-form>
        <van-cell-group>
          <van-field
            v-model="testCode"
            disabled
            :label="translateTitle('Ve.elements.动态输入')"
            :name="动态输入"
            :placeholder="translateTitle('Ve.elements.动态输入')"
          />
          <van-field
            v-model="testCode"
            disabled
            :label="translateTitle('Ve.elements.动态下拉')"
            :name="动态下拉"
            :placeholder="translateTitle('Ve.elements.动态下拉')"
          />
          <van-field
            v-model="testCode"
            disabled
            :label="translateTitle('Ve.elements.动态日历')"
            :name="动态日历"
            :placeholder="translateTitle('Ve.elements.动态日历')"
          />
        </van-cell-group>
      </van-form>
    </div>
  </template>

  <template v-else>
    <div :ref="'self' + info._id" v-ui-ref="vSetRef" class="ui-dynamic-form" :class="{ hidden: conditionProperty.hidden }">
      <pdaWidget v-if="isShowBatch && info.list.length != 0" :class="['grid cols-2']" :list="info.list" />
      <!-- <van-empty description="暂无批次数据" /> -->
    </div>
  </template>
</template>
<script>
  import { translateTitle } from '@/utils/i18n'
  import { defineComponent, defineAsyncComponent } from 'vue'
  import { UiMixin, ElementsFormMixin, RefsInjectMixin } from '@ve/mixin'
  import COMPONENTS from '@ve/common/components'
  import isArray from 'lodash/isArray'
  import cloneDeep from 'lodash/cloneDeep'
  import request from '@/utils/request'
  import { reArrayData } from '@ve/utils/extendData'
  import { GFCD } from '@/utils/utils'
  import { processingConstant } from '@ve/utils/utils'
  import { componentId } from '@/utils/unique'
  import isEmpty from 'lodash/isEmpty'
  import trim from 'lodash/trim'
  import dayjs from 'dayjs'
  import { Field, Form, CellGroup, Icon, Empty } from 'vant'
  import debounce from 'lodash/debounce'

  const componentARR = {
    10: 'uiPdaInput',
    20: 'uiPdaInput',
    30: 'uiPdaInput',
    40: 'uiPdaTimePicker', //日期下拉
    50: 'uiPdaTimePicker', //日期时间下拉
    60: 'uiPdaDateTimeInput', //日期输入
    70: 'uiPdaDateTimeInput', //日期时间输入
  }

  export default defineComponent({
    name: 'UiPdaBatch',
    components: {
      // 使用异步组件
      pdaWidget: defineAsyncComponent(() => import('@ve/components/pdaWidget.vue')),
      [Field.name]: Field,
      [Form.name]: Form,
      [CellGroup.name]: CellGroup,
      [Icon.name]: Icon,
      [Empty.name]: Empty,
    },
    mixins: [UiMixin, ElementsFormMixin, RefsInjectMixin],
    props: {
      requestFlag: {
        type: Number,
        default: 0,
      },
      info: {
        required: true,
        type: Object,
        default: function () {
          return {}
        },
      },
    },
    data: function () {
      return {
        testCode: '',
        testNumber: 0,
        dataSorce: {},
        lastNewval: {},
        defaultValues: [], //默认值
        isShowBatch: true, // 是否显示批次
        conditionProperty: {
          disabled: false,
          hidden: false,
        },
        focusIdArr: [],
        // flag: false,
      }
    },
    computed: {
      requestData() {
        console.log('批次属性1', this.info.data.requestData.data)
        // this.initFuc()

        return this.info.data.requestData.data ? this.info.data.requestData.data : []
      },
      moduleList() {
        return this.info.list
      },
    },
    watch: {
      // requestFlag: {
      //   handler() {
      //     this.renderDynamicForm(this)
      //   },
      // },
      requestData: {
        deep: true,
        handler(newvalue) {
          console.log('批次属性2', newvalue)
          this.initFuc()
        },
      },
      moduleList: {
        deep: true,
        handler(newvalue) {
          if (newvalue.hidden) this.getInfo.list = []
        },
      },
    },
    created() {
      if (!this.hasPreview) this.getInfo.list = []
      this.defaultValues = (this.getInfo.extension.defaultValues && this.getInfo.extension.defaultValues.value) || []
    },
    methods: {
      initFuc: debounce(function () {
        this.renderDynamicForm(this, this.info.data.requestData.data)
      }, 500),
      translateTitle,
      requestApi(options = {}, callback) {
        if (!options.api || !options.method || !options.key) {
          return
        }
        let Request = {},
          requestValue = options.data
        requestValue.forEach((v) => {
          Request[v.key] = v.value
        })
        if (options.selectConfig) {
          Request.CODE = options.selectConfig
        }
        // 下拉接口
        //发起请求
        return request({
          url: GFCD('dams', 'domain') + options.api,
          method: 'post',
          data: {
            data: JSON.stringify(Request),
            method: options.method,
          },
        }).then((res) => {
          //添加回调
          callback && callback.call(this, res)
        })
      },
      //异步执行渲染组件
      async renderDynamicForm(vm, data) {
        this.focusIdArr = []
        const $this = vm
        if (!$this.hasPreview) {
          return
        }
        if ($this.vuiComponents[$this.formId]) {
          const formItems = $this.vuiComponents[$this.formId].self.getInfo.data.formItems || {}
          for (let key in formItems) {
            if (formItems[key].indexOf('UiPdaBatchLOT_') !== -1) {
              delete formItems[key]
            }
          }
        }
        $this.getInfo.list = []
        const components = reArrayData([COMPONENTS.pdaComs], [])
        let result = [],
          dataArr = data || $this.getInfo.data.requestData.data || []
        //拼接组装数据
        for (let i = 0; i < dataArr.length; i++) {
          const item = dataArr[i]
          if (item.INPUT_CONTROL_TYPE == '40') {
            continue
          }
          let obj = {}
          //判断类型
          obj = components.find((comp) => {
            let type = componentARR[item.INPUT_FORMAT_TYPE]
            //判断是不是下拉
            if (item.INPUT_OPTIONS) {
              type = 'uiPdaSelect'
            }
            return comp.type === type
          })
          // Nico 下拉处理
          if (item.INPUT_OPTIONS && item.INPUT_CONTROL_TYPE != '40') {
            await $this.requestApi(
              {
                api: $this.info.extension.apiDropdown.value,
                method: $this.info.extension.methodDropdown.value,
                key: $this.info.extension.getDataKeyDropdown.value,
                data: $this.getInfo.extension.requestDataDropdown.value,
                selectConfig: item.INPUT_OPTIONS,
              },
              function (data) {
                if (!data.data || !data.data[$this.info.extension.getDataKeyDropdown.value]) {
                  obj.extension.optionConfig.value = []
                  return
                }
                //   //设置key和value
                obj.extension.labelField.value = ($this.info.extension.labelField || { value: 'label' }).value
                obj.extension.valueField.value = ($this.info.extension.valueField || { value: 'value' }).value
                obj.extension.optionConfig.value = data.data[$this.info.extension.getDataKeyDropdown.value].data || []
              }
            )
          }
          if (obj) {
            obj.formData = obj.formData || {}
            obj = cloneDeep(obj)
            obj._id = 'UiPdaBatch_' + obj.type + '_' + componentId(6)
            //字段
            obj.extension.model.value = $this.getprefix($this) + item.LOT_SEQ
            //名称
            obj.extension.label.value = item.LOT_SEQ_NAME
            //赋默认值
            if ($this.defaultValues.length) {
              const findDefalut = $this.defaultValues.find((defalutvalue) => {
                return defalutvalue.key === item.LOT_SEQ
              })

              if (findDefalut) {
                //没有默认值的情况赋值对象
                obj.extension.defaultValue = obj.extension.defaultValue || {}
                //赋默认值
                obj.extension.defaultValue.value = $this.getDefaultValue($this, findDefalut.value)
              }
            }
            //不是下拉选执行
            if (!item.INPUT_OPTIONS) {
              //日期类型
              // Nico 操作时间组件
              item.INPUT_FORMAT_TYPE == '40' && (obj.extension.moduleType.value = 'date')
              // //日期时间类型
              item.INPUT_FORMAT_TYPE == '50' && (obj.extension.moduleType.value = 'datetime')
              // 如果是日期时间输入
              item.INPUT_FORMAT_TYPE == '60' && (obj.extension.moduleType.value = 'date')
              item.INPUT_FORMAT_TYPE == '70' && (obj.extension.moduleType.value = 'datetime')
              // CUR_LOT
            }
            //验证相关逻辑
            if (item.INPUT_CONTROL_TYPE == '30' || $this.info.extension.disabled.value) {
              obj.extension.disabled.value = true
            } else if (item.INPUT_CONTROL_TYPE == '20') {
              obj.extension.extendRule.value.ChangeSwitch = true
              obj.extension.extendRule.value.required = true
            }
            if (item.CUR_LOT === 'Y' && item.INPUT_CONTROL_TYPE != '30') {
              obj.extension.CUR_LOT = 'Y'
              obj._PId = $this.info._id
              this.focusIdArr.push(obj)
              console.log('$this.info', item)
            }
            //

            result.push(obj)
          }
        }
        $this.getInfo.list = result
      },
      getIgnoreValidation(key) {
        if (
          this.info.extension.IgnoreValidation &&
          this.info.extension.IgnoreValidation.value.length > 0 &&
          this.info.extension.IgnoreValidation.value.split(',').find((el) => el == key)
        ) {
          //忽略验证
          return false
        } else {
          return true
        }
      },
      getprefix(vm) {
        let returnObj = vm.info.extension.prefix || { value: '' }
        return returnObj.value || ''
      },
      dataSourceChange(newval) {
        // 判断是否有值改变
        let changeFlag = false
        Object.keys(newval).map((v) => {
          if (newval[v] !== this.lastNewval[v]) {
            changeFlag = true
          }
        })
        if (changeFlag) {
          this.lastNewval = cloneDeep(newval)
        } else {
          // 如果值未改变则不进行后续操作
          return
        }
        let _obj = {}
        Object.keys(this.getInfo.data.formData).map((v) => {
          _obj[v] = ''
        })
        let _mergeData = {}
        // 根据 getDataKey 筛选需要的数据
        if (!trim(this.info.dataSourceBind.getDataKey?.value)) {
          // 如果没有 getDataKey 则返回全量数据
          _mergeData = newval
        } else {
          const keyList = this.info.dataSourceBind.getDataKey?.value.split(',')
          isArray(keyList) &&
            keyList.forEach((item) => {
              item = trim(item)
              if (newval[item] !== undefined) {
                // 如果传过来的对象里面没有要取得值 则丢弃
                _mergeData[item] = newval[item]
              }
            })
        }
        let _data = isEmpty(_mergeData)
          ? _obj
          : {
              ...this.getInfo.data.formData,
              ..._mergeData,
            }
        this.getInfo.data.formData = _data
        this.dataSorce = _data
      },
      //获取自定义请求参数
      $getRequestData() {
        let _data = { ...this.dataSorce }
        const requestData = this.info.extension.requestData
        if (requestData && isArray(requestData.value)) {
          requestData.value.forEach((item) => {
            let itemVal = item.value
            if (/{[^#{]+}/g.test(itemVal)) {
              //获取索引
              const index = itemVal.indexOf('}')
              //获取字段
              const field = itemVal.substring(2, index) + itemVal.substring(index + 1)
              //赋值
              itemVal = this.dataSorce[field]
            }
            _data[item.key] = processingConstant(this, itemVal)
          })
        }
        return _data
      },

      //常量处理
      processingConstant() {
        let _defValue = trim(this.info.extension.defaultValue.value)
        let _getConstant = this.$store.getters['user/getConstant']
        let _value = ''
        switch (_defValue) {
          case '#USER_ID#':
            _value = this.$store.getters['user/uid']
            break
          case '#TOKEN#':
            _value = this.$store.getters['user/token']
            break
          case '#USER_NAME#':
            _value = this.$store.getters['user/username']
            break
          case '#ORG_ID#':
            _value = _getConstant['#ORG_ID#']
            break
          case '#APP_ID#':
            _value = this.$store.getters['user/appId']
            break
          case '#APP_CODE#':
            _value = this.$store.getters['user/appCode']
            break
          case '#WH_ID#':
            _value = _getConstant['#WH_ID#']
            break
          case '#LANGUAGE_CODE#':
            _value = this.$store.getters['user/language']
            break
          case '#AUTH_WH_ID#':
            _value = _getConstant['#AUTH_WH_ID#']
            break
          case '#AUTH_OWNER_ID#':
            _value = _getConstant['#AUTH_OWNER_ID#']
            break
          case '#AUTH_ORG_ID#':
            _value = _getConstant['#AUTH_ORG_ID#']
            break
          case '#AUTH_ORDER_RCV#':
            _value = _getConstant['#AUTH_ORDER_RCV#']
            break
          case '#AUTH_ORDER_SO#':
            _value = _getConstant['#AUTH_ORDER_SO#']
            break
          case '#AUTH_ORDER_CC#':
            _value = _getConstant['#AUTH_ORDER_CC#']
            break
          case '#AUTH_ORDER_ADJ#':
            _value = _getConstant['#AUTH_ORDER_ADJ#']
            break
          case '#AUTH_ORDER_MOV#':
            _value = _getConstant['#AUTH_ORDER_MOV#']
            break
          case '#AUTH_ORDER_TSF#':
            _value = _getConstant['#AUTH_ORDER_TSF#']
            break
          case '#AUTH_ORDER_FRZ#':
            _value = _getConstant['#AUTH_ORDER_FRZ#']
            break
          default:
            _value = _defValue
            break
        }
        return _value
      },
      //获取默认值
      getDefaultValue(vm, value) {
        switch (value) {
          case '#CURRENT_DATE#':
            value = dayjs().format('YYYY-MM-DD')
            break
          case '#CURRENT_DATETIME#':
            value = dayjs().format('YYYY-MM-DD HH:mm:ss')
            break
          default:
            value = processingConstant(vm, value)
            break
        }
        return value
      },
      //禁用状态
      $isDisabled(flag) {
        //flag = true：禁用 flag = false：启用
        const list = this.getInfo.list || []
        for (let i = 0; i < list.length; i++) {
          if (!list[i].extension.disabled) {
            list[i].extension.disabled = {}
          }
          list[i].extension.disabled && (list[i].extension.disabled.value = flag)
        }
      },
      // 获取批次属性表单值
      getLotValue() {
        // 1. 先查找到当前组件所在得表单组件
        // this里面有一个 formId 属性存储了当前组件所在的表单组件的 id，直接取来用即可
        // 通过 formId 在 vuiComponents 中找到表单组件的实例
        const formSelf = this.vuiComponents[this.formId] && this.vuiComponents[this.formId].self
        // 2. 在表单组件中获取LOT01 ~ LOT48的值，然后返回
        if (!formSelf) return {}
        let respObj = {}
        // 在表单实例中拿到表单的值
        const fromData = formSelf.info.data.formData
        // 将表单中的值写入返回对象并返回
        for (let i = 1; i < 49; i++) {
          let ii = i < 10 ? '0' : ''
          respObj[`LOT${ii}${i}`] = fromData[`LOT${ii}${i}`] == undefined ? '' : fromData[`LOT${ii}${i}`]
        }
        return respObj
      },
    },
  })
</script>
<style scoped>
  .batchHeader {
    padding-left: 5%;
    font-size: 0.6rem;
    padding-bottom: 4%;
  }
</style>
